# -*- coding : utf-8 -*-

from PySide2.QtWidgets import QApplication, QDialog, QHeaderView, QMessageBox
from PySide2.QtCore import Qt, QThread, Signal

import sys
import time

from ui.ui_login import Ui_Dialog


class LoginWindow(QDialog, Ui_Dialog):
    def __init__(self, session, parent=None):
        self.parent = parent
        self.session = session
        super().__init__()
        self.task_post = None
        self.task_flag = True # 可以运行
        self.setupUi(self)
        self.pushButton_login.clicked.connect(self.submit_widget_data)
        self.pushButton_back.clicked.connect(self.close)
        self.setWindowModality(Qt.ApplicationModal)
        self.setWindowFlags(Qt.WindowCloseButtonHint)
    
    def submit_widget_data(self):
        username = self.lineEdit_name.text()
        password = self.lineEdit_password.text()
        
        if username == "" or password == "":
            QMessageBox.information(self, '信息', '用户名或者密码不能为空！', QMessageBox.Ok)
            return
        data_dict = {
            'username': username,
            'password': password,
        }
        if self.task_flag:
            self.task_post = PostData(self.session, data_dict)
            self.task_post.signal_done[str].connect(self.show_add_result)
            self.task_post.start()
            self.task_flag = False
        
    def show_add_result(self, string):
        if string == "ok":
            QMessageBox.information(self, '信息', '登录成功！', QMessageBox.Ok)
            self.close()
        else:
            QMessageBox.information(self, '信息', '登录失败！', QMessageBox.Ok) 
        self.task_flag = True
        # print(self.session.session)
    

# 提交数据
class PostData(QThread):
    
    signal_done = Signal(str)
    
    def __init__(self, session, data):
        super().__init__()
        self.session = session
        self.data = data
    
    def run(self):

        resp = None
        
        try:
            resp = self.session.requests.post(
                'http://127.0.0.1:8008/user/login/',
                data = self.data,
                allow_redirects=False,
                timeout = 3,
            )
        except Exception as e:
            self.signal_done.emit(str(e))
        else:
            self.session.session = dict(sessionid=resp.cookies.get('sessionid'))
            if self.session.session:
                self.signal_done.emit('ok')
            else:
                self.signal_done.emit('error')


if __name__ == "__main__":
    # 开始运行
    import requests
    app = QApplication(sys.argv)
    winMain = MdiAddWindow(requests)
    winMain.show()
    # winMain.setMouseTracking(True) # 鼠标跟随
    app.exec_()